package com.jiahao.material.exceptions;


import com.jiahao.material.entity.Result;
import com.jiahao.material.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandle {



    @ExceptionHandler(value = AuthorizationException.class)
    @ResponseBody
    public Result authException(AuthorizationException e) {
        Result result = ResultUtil.noAuthc("");
        String message = e.getMessage();
        String msg=message.substring(message.indexOf("[")+1,message.indexOf("]"));
        //判断是角色错误还是权限错误
        if (message.contains("role")) {
            result.setMessage( "对不起，您没有" + msg + "角色");
        } else if (message.contains("permission")) {
            result.setMessage( "对不起，您没有" + msg + "权限");
        } else {
            result.setMessage( "对不起，您的权限有误");
        }
        return result;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exception(Exception e){
        log.error("====>运行时异常:"+e.getMessage());
        return ResultUtil.fail("服务器异常!请稍后尝试!");
    }

}
